<template>
  <template v-if="isArray">
    <el-space wrap>
      <div v-for="(item,i) in imageUrl" class="imgs_box" :key="item">
        <img  :src="item" class="avatars" />
        <div class="hover_del">
          <el-icon size="40px" @click="delImags(i)" color="#eee">
            <Delete />
          </el-icon>
        </div>
      </div>
      <el-upload
          class="avatar-uploader"
          action="/jeecg-boot/jx/ossAdmin/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <el-icon  class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-space>

  </template>
  <template v-else>
    <el-upload
        class="avatar-uploader"
        action="/jeecg-boot/jx/ossAdmin/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </template>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const imageUrl = defineModel('imageUrl')
// 判断传值是否是数组
const  isArray = Array.isArray(imageUrl.value)
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  if(isArray) {
    imageUrl.value.push(response.message)
    return
  }else{
    imageUrl.value = response.message
  }
}

const beforeAvatarUpload = (rawFile) => {
  // if (/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name) ) {
    // console.log(rawFile);
  // }
  if (!rawFile.type.includes('image')) {
    ElMessage.error('请上传正确的图片文件')
    return
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于2MB!')
    return false
  }
  return true
}

const  delImags = (index) => {
  imageUrl.value.splice(index, 1)
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatars {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.imgs_box {
  width: 178px;
  height: 178px;
  position: relative;
  cursor: pointer;
}
.hover_del{
  display: none;
  position: absolute;
  width: 178px;
  height: 178px;
  left: 0;
  top: 0;
  background: #00000080;
  align-items: center;
  justify-content: center;
}
.imgs_box:hover .hover_del {
  display: flex;
}


</style>
